/**
 * Created by dukes on 2015/12/11.
 */
class PerformanceMonitor {
    public inLowModel:boolean = false;
    public static MUSIC = 0;
    public static SOUND = 1;
    public static EFFECTS = 2;
    private frameItem:FrameItem;
    private setupMap;
    public name:string;
    public constructor(){
        this.name = "performancemonitor";
        this.init();
    }
    /**
     * 获取开关状态
     * **/
    public getSwithState(type:number){
        return this.setupMap[type];
    }

    public setSwithState(type:number,value:boolean){
        this.setupMap[type] = value;
        this.inLowModel = this.inLowModel && value;
        EventController.getInstance().dispatchEventWith(EventController.LOW_FRAMERATE,false,type);
    }

    private totalTime:number = 0;
    private totalTick:number = 0;
    private countGap:number = 10;//连续10帧
    private countTotal:number = 0;//10帧消耗的时间
    private update(delta:number){
        this.totalTime += delta;
        this.totalTick++;
        if (this.totalTime > 500) {
            var lastFPS = Math.round(this.totalTick * 1000 / this.totalTime);
            this.totalTick = 0;
            this.totalTime -= 500;

            this.countGap--;
            this.countTotal += lastFPS;
            if( this.countGap <= 0 && !this.inLowModel){
                var checkFps = Math.floor(this.countTotal/(10+Math.abs(this.countGap)));
                this.countGap = 10;
                this.countTotal = 0;
                if( checkFps < 30){
                    this.inLowModel = true;
                    this.setupMap = {0:true,1:true,2:true};
                    EventController.getInstance().dispatchEventWith(EventController.LOW_FRAMERATE,false,-1);
                    FrameMgr.getInstance().delController(this.name);
                }
            }
        }
    }

    private init(){
        if( !Model.getStateFromMask(GameConst.MARK_FORIDE_LOWMODEL)){
            this.frameItem = new FrameItem();
            this.frameItem.callObj = this;
            this.frameItem.callFun = this.update;
        }
        this.setupMap = {};
        this.setupMap[0] = Model.getStateFromMask(GameConst.MARK_MUSIC);
        this.setupMap[1] = Model.getStateFromMask(GameConst.MARK_SOUND);
        this.setupMap[2] = Model.getStateFromMask(GameConst.MARK_EFFECT);
    }

    public start(){
        if( !Model.getStateFromMask(GameConst.MARK_FORIDE_LOWMODEL)) {
            FrameMgr.getInstance().addControll(this.frameItem);
        }
    }

    private static _instance:PerformanceMonitor;
    public static getInstance():PerformanceMonitor{
        if( PerformanceMonitor._instance == null)
            PerformanceMonitor._instance = new PerformanceMonitor();
        return PerformanceMonitor._instance;
    }
}